<template>
  <div ref="chartDom" class="chart"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { fetchCategorySales } from '@/api/data';

const chartDom = ref(null);
let myChart = null;

const option = ref({
  title: {
    text: '各类目销量占比',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: []
  },
  series: [
    {
      name: '销量占比',
      type: 'pie',
      radius: '50%',
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      itemStyle: {
        borderRadius: 5,
        borderColor: '#fff',
        borderWidth: 2
      }
    }
  ]
});

// 初始化图表
const initChart = () => {
  if (chartDom.value) {
    myChart = echarts.init(chartDom.value);
    myChart.setOption(option.value);
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  myChart?.resize();
};

// 获取数据并更新图表
const updateChart = async () => {
  const data = await fetchCategorySales();
  option.value.legend.data = data.map(item => item.categoryName);
  option.value.series[0].data = data.map(item => ({
    value: item.totalSales,
    name: item.categoryName
  }));
  
  if (myChart) {
    myChart.setOption(option.value);
  }
};

onMounted(() => {
  initChart();
  updateChart();
});

onBeforeUnmount(() => {
  // 移除事件监听
  window.removeEventListener('resize', handleResize);
  // 销毁图表实例
  myChart?.dispose();
});
</script>

<style scoped>
.chart {
  height: 100%;
  width: 100%;
  min-height: 400px; /* 确保图表有最小高度 */
}
</style>